package com.ysh.xiaomi.dao.impl;

import com.ysh.xiaomi.dao.CartDao;
import com.ysh.xiaomi.pojo.TbCart;
import com.ysh.xiaomi.utils.DbUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.SQLException;
import java.util.List;

/**
 * 袁胜虎 on 2022/8/18 17:19
 */
public class CartDaoImpl implements CartDao {
    @Override
    public TbCart findByUserIdAndGoodId(Long userId, Long goodId) {
        QueryRunner qr = new QueryRunner();
        String sql = "select * from tb_cart where id=? and pid=?";
        try {
            TbCart cart = qr.query(DbUtils.getConn(), sql, new BeanHandler<>(TbCart.class), userId, goodId);
            return cart;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public int addCart(Long userId, Long goodId, int num) {
        QueryRunner qr = new QueryRunner();
        String sql = "insert into tb_cart values(?,?,?,null)";
        try {
            int update = qr.update(DbUtils.getConn(), sql, userId, goodId,num);
            return update;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 0;
    }

    @Override
    public int updateCount(Long userId, Long goodId, int num) {
        QueryRunner qr = new QueryRunner();
        String sql="update tb_cart set num = num+? where id=? and pid=?";
        try {
            return  qr.update(DbUtils.getConn(),sql,num,userId,goodId);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 0;
    }

    @Override
    public List<TbCart> findByUserId(Long userId) {
        QueryRunner qr = new QueryRunner();
        String sql = "select pid,num from tb_cart where id=?";
        //查询某个用户的购物车数据
        try {
            List<TbCart> cartList = qr.query(DbUtils.getConn(), sql, new BeanListHandler<>(TbCart.class), userId);
            return cartList;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public void clearCart(Long userId) {
        QueryRunner qr = new QueryRunner();
        String sql = "delete from tb_cart where id = ?";
        try {
            qr.update(DbUtils.getConn(),sql,userId);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void deleteBycart(Long userId) {
        QueryRunner qr = new QueryRunner();
        String sql = "delete from tb_cart where id = ?";
        try {
            qr.update(DbUtils.getConn(),sql,userId);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
